package com.czl.module_storehouse.activity.remand.details;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.czl.base.data.bean.tengyun.ReceiveBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.base.data.bean.tengyun.SortBeanType;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.utils.ParcelHelper;
import com.czl.module_service.event.DamageRegisBackEvent;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.activity.base.BaseOperationActivity;
import com.czl.module_storehouse.activity.intostore.saveloc.SaveLocActivity;
import com.czl.module_storehouse.activity.remand.damage.DamageRegisActivity;
import com.czl.module_storehouse.activity.remand.damage.DamageRegisProductActivity;
import com.czl.module_storehouse.activity.remand.scan.RemandScanActivity;
import com.czl.module_storehouse.adapter.RemandNeedAdapter;
import com.czl.module_storehouse.bean.ReceiveReturnNeedBean;
import com.czl.module_storehouse.bean.RemandBean;
import com.czl.module_storehouse.databinding.ActivityBaseOperationBinding;
import com.czl.module_storehouse.databinding.FooterCommonRemarkBinding;
import com.czl.module_storehouse.databinding.HeaderRemandReceiveNeedBinding;
import com.czl.module_storehouse.event.AllocateScanBackEvent;
import com.czl.module_storehouse.event.DamageRegisEvent;
import com.czl.module_storehouse.event.DamageRegisPostEvent;
import com.czl.module_storehouse.event.RemandEvent;
import com.czl.module_storehouse.event.RemandScanEvent;
import com.czl.module_storehouse.event.SaveLocationEvent;
import com.czl.module_storehouse.mvp.presenter.RemandHomePresenter;
import com.czl.module_storehouse.mvp.view.RemandHomeView;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xubin
 */
public class RemandReceiveNeedActivity extends BaseOperationActivity<ActivityBaseOperationBinding> implements
        RemandHomeView, RemandNeedAdapter.OnNumberChangedListener {

    private final ReceiveReturnNeedBean mReceiveReturnBean = new ReceiveReturnNeedBean();

    private SortBean mSelectSortBean;
    private RemandNeedAdapter mAdapter;
    @InjectPresenter
    RemandHomePresenter mRemandHomePresenter;

    private HeaderRemandReceiveNeedBinding mHeaderBinding;
    private FooterCommonRemarkBinding mFooterBinding;

    private RemandBean mRemandBean;

    @Override
    protected ActivityBaseOperationBinding getBinding(LayoutInflater layoutInflater) {
        return ActivityBaseOperationBinding.inflate(layoutInflater);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mToolBinding.toolbarContentTitle.setText("领用归还");
        binding.btnSure.setText("归还入库");
        binding.recyclerView.setAdapter(getAdapter());
        LiveEventBus.get(DamageRegisBackEvent.class).observe(this, event -> setDamageRegisSortBean(event.getSortBean()));
    }

    @Override
    protected BaseQuickAdapter<SortBean, ?> getAdapter() {
        if (mAdapter == null) {
            mAdapter = new RemandNeedAdapter(new ArrayList<>(), RemandNeedAdapter.TAG_RECEIVE, this);
            mHeaderBinding = HeaderRemandReceiveNeedBinding.inflate(getLayoutInflater());
            mAdapter.addHeaderView(mHeaderBinding.getRoot());
            mFooterBinding = FooterCommonRemarkBinding.inflate(getLayoutInflater());
            mAdapter.addFooterView(mFooterBinding.getRoot());
            mAdapter.setOnItemChildClickListener((adapter, view, position)
                    -> startActivity(position, view));
        }
        return mAdapter;
    }

    @Override
    protected void startActivity(int position, View view) {
        mSelectedPosition = position;
        SortBean sortBean = mAdapter.getData().get(position);
        if (R.id.cl_root == view.getId()) {
            goRemandActivity(sortBean);
        } else if (R.id.tv_loc == view.getId()) {
            goRemandActivity(sortBean);
        } else if (R.id.tv_damage_num == view.getId()) {
            goDamageActivity(sortBean);
        }
    }

    @Override
    protected Button getButton() {
        return binding.btnSure;
    }

    @SuppressLint("SetTextI18n")
    private void initHeaderView(ReceiveBean receiveBean) {
        mHeaderBinding.clHeaderInfo.tvHeaderTitle.setText(receiveBean.getReceiveName());
        mHeaderBinding.clHeaderInfo.tvHeaderDate.setText(receiveBean.getReceiveDate());
        mHeaderBinding.clHeaderInfo.tvHeaderCode.setText(receiveBean.getReceiveCode("领用单："));
        mHeaderBinding.tvHeaderDepartment.setText("领用部门：" + receiveBean.getReceivePersonDepartment());
        mHeaderBinding.tvHeaderDesc.setText("领用原因：" + receiveBean.getApplyComment());
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(RemandEvent event) {
        if (event != null) {
            mRemandBean = event.getRemandBean();
            if (mRemandBean != null && mRemandBean.getReceiveBean() != null) {
                ReceiveBean receiveBean = mRemandBean.getReceiveBean();
                initHeaderView(receiveBean);
                receiveBean = ParcelHelper.copy(receiveBean);
                List<SortBean> sortList = receiveBean.getSortList();
                setAdapterData(sortList);
            }
        }
    }

    private void setAdapterData(List<SortBean> sortList) {
        List<SortBean> newList = new ArrayList<>();
        if (getAdapter() != null && sortList != null) {
            for (SortBean bean : sortList) {
                bean.setLocatList(null);
                if (bean.pasteCode()) {
                    bean.setItemViewType(SortBeanType.Type.VIEW_TYPE_PRODUCT);
                }
                if (bean.getAllocatedInNum() <= 0) {
                    continue;
                }
                newList.add(bean);
            }
            getAdapter().setList(newList);
        }
    }

    @Override
    protected void handleSelectedGoods(List<SortBean> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        for (SortBean sortBean : list) {
            if (sortBean.pasteCode()) {
                sortBean.setItemViewType(SortBeanType.Type.VIEW_TYPE_PRODUCT);
            }
        }
        super.handleSelectedGoods(list);
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        if (RemandHomePresenter.TAG_REMAND_RECEIVE.equals(httpResponse.getRequestTag())) {
            showToast("归还成功");
            EventBus.getDefault().postSticky(new RemandEvent(RemandEvent.RECEIVE));
            finish();
        }
    }

    /**
     * 损坏登记
     *
     * @param sortBean
     */
    private void goDamageActivity(SortBean sortBean) {
        mSelectSortBean = sortBean;
        EventBus.getDefault().postSticky(new DamageRegisEvent(sortBean, mRemandBean));
        if (1 == sortBean.manageMode() && sortBean.pasteCode()) {
            startActivity(new Intent(getContext(), DamageRegisProductActivity.class));
        } else {
            startActivity(new Intent(getContext(), DamageRegisActivity.class));
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(DamageRegisPostEvent event) {
        SortBean sortBean = event.getSortBean();
        if (sortBean == null) {
            return;
        }
        mSelectSortBean.setExcNum(sortBean.getExcNum());
        mSelectSortBean.setExcLossesNum(sortBean.getExcLossesNum());
        mSelectSortBean.setExcLocatId(sortBean.getExcLocatId());
        mSelectSortBean.setExcLocatName(sortBean.getExcLocatName());
        mSelectSortBean.setDamageComment(sortBean.getDamageComment());
        mSelectSortBean.setExcProductList(sortBean.getExcProductList());
        mAdapter.setData(mSelectedPosition, mSelectSortBean);
        binding.btnSure.setEnabled(sortBean.excNum() > 0);
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(AllocateScanBackEvent event) {
        SortBean sortBean = event.getSortBean();
        if (sortBean == null) {
            return;
        }
        getAdapter().setData(mSelectedPosition, sortBean);
        setButtonState(getTotalRemandCount());
    }

    private void setDamageRegisSortBean(SortBean sortBean) {
        if (sortBean == null) {
            return;
        }
        mSelectSortBean.setExcNum(sortBean.getExcNum());
        mSelectSortBean.setExcLossesNum(sortBean.getExcLossesNum());
        mSelectSortBean.setExcLocatId(sortBean.getExcLocatId());
        mSelectSortBean.setExcLocatName(sortBean.getExcLocatName());
        mSelectSortBean.setDamageComment(sortBean.getDamageComment());
        mSelectSortBean.setExcProductList(sortBean.getExcProductList());
        mAdapter.setData(mSelectedPosition, mSelectSortBean);
        setButtonState();
    }

    /**
     * 选择位置
     *
     * @param sortBean
     */
    private void goLocActivity(SortBean sortBean) {
        EventBus.getDefault().postSticky(new SaveLocationEvent(sortBean, sortBean.getRemandNum(), true));
        startActivity(new Intent(getContext(), SaveLocActivity.class));
    }

    private void goRemandActivity(SortBean sortBean) {
        RemandScanEvent event = new RemandScanEvent(mRemandBean, sortBean);
        EventBus.getDefault().postSticky(event);
        if (sortBean.pasteCode()) {
            startActivity(new Intent(getContext(), RemandScanActivity.class));
        } else {
            goLocActivity(sortBean);
        }
    }

    @Override
    protected void submit() {
        List<SortBean> data = mAdapter.getData();
        for (SortBean sortBean : data) {
            if (sortBean.pasteCode() && sortBean.excNum() > 0
                    && (sortBean.getProductCount() + sortBean.excNum()) < sortBean.getRemandNum()) {
                showToast("物品" + sortBean.getSortName() + "未完成归还不能登记损坏！");
                return;
            }
        }

        mReceiveReturnBean.setSortList(data);
        String remark = mFooterBinding.etRemark.getText().toString();
        mReceiveReturnBean.setReturnComment(remark);
        if (mRemandBean != null) {
            ReceiveBean receiveBean = mRemandBean.getReceiveBean();
            if (receiveBean != null) {
                int receiveId = receiveBean.getReceiveId();
                mReceiveReturnBean.setReceiveId(receiveId);
            }
        }
        if (mRemandHomePresenter != null) {
            mRemandHomePresenter.receiveReturn(mReceiveReturnBean);
        }
    }

    @Override
    public void textChange(SortBean sortBean) {
        setButtonState(getTotalRemandCount());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHeaderBinding != null) {
            mHeaderBinding.unbind();
        }
        if (mFooterBinding != null) {
            mFooterBinding.unbind();
        }
    }
}
